package com.jic.product.impl;

import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.product.entity.Category;
import com.jic.product.entity.CategoryMerchantRelation;
import com.jic.product.manage.request.CategoryMerchantRelationRequest;
import com.jic.product.manage.response.CategoryResponse;
import com.jic.product.mapper.CategoryMapper;
import com.jic.product.mapper.CategoryMerchantRelationMapper;
import com.jic.product.mapper.CategoryTreeNodeRelationMapper;
import com.jic.product.service.CategoryMerchantRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商家店铺类目关联表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-08-14 10:33:16
 */
@Service
@Slf4j
public class CategoryMerchantRelationServiceImpl implements CategoryMerchantRelationService {

    @Autowired
    private CategoryMerchantRelationMapper categoryMerchantRelationMapper;

    @Autowired
    private CategoryTreeNodeRelationMapper categoryTreeNodeRelationMapper;

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public long insert(CategoryMerchantRelation categoryMerchantRelation) {
        long flag = categoryMerchantRelationMapper.insert(categoryMerchantRelation);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return categoryMerchantRelationMapper.delete(id);
    }

    @Override
    public long update(CategoryMerchantRelation categoryMerchantRelation) {
        return categoryMerchantRelationMapper.update(categoryMerchantRelation);
    }

    @Override
    public CategoryMerchantRelation queryByPrimaryKey(Long id) {
        return categoryMerchantRelationMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<CategoryMerchantRelation> query(CategoryMerchantRelation categoryMerchantRelation) {
        return categoryMerchantRelationMapper.query(categoryMerchantRelation);
    }

    @Override
    public PageResult<CategoryMerchantRelation> queryPage(CategoryMerchantRelation categoryMerchantRelation, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<CategoryMerchantRelation> list = categoryMerchantRelationMapper.queryPage(startIndex, pageQuery.getLimit(), categoryMerchantRelation);
        long count = categoryMerchantRelationMapper.queryPageCount(categoryMerchantRelation);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<List<CategoryResponse>> queryStoreSecondCategory(Long deptId) {
        log.info("jic-product===============》查询店铺二级分类,{}", deptId);
        try {
            List<CategoryResponse> categoryResponseList = new ArrayList<>();
            //查询当前店铺的所有后台类目
            CategoryMerchantRelation categoryMerchantRelation = new CategoryMerchantRelation();
            categoryMerchantRelation.setDeptId(deptId);
            categoryMerchantRelation.setType(2);
            categoryMerchantRelation.setIsDisplay(1);
            List<CategoryMerchantRelation> list = categoryMerchantRelationMapper.query(categoryMerchantRelation);
            List<Long> categoryIds = new ArrayList<>();
            list.forEach(item -> {
                categoryIds.add(item.getCategoryId());
            });
            if (CollectionUtils.isNotEmpty(categoryIds)) {
                List<String> leftId = categoryTreeNodeRelationMapper.queryLeftIdByRightId(categoryIds);
                Category categoryRest = new Category();
                categoryRest.setType(2);
                categoryRest.setDeleteFlag(0);
                final List<Category> categoryAllRestList = categoryMapper.query(categoryRest);
                if (CollectionUtils.isNotEmpty(leftId)) {
                    leftId.forEach(item -> {
                        List<Category> categoryList = new ArrayList<>();
                        Category category = categoryMapper.queryByPrimaryKey(Long.valueOf(item));
                        Category category1 = getParentCategoryObject(category, categoryAllRestList);
                        if (category1 != null) {
                            CategoryResponse categoryResponse = new CategoryResponse();
                            BeanUtils.copyProperties(category1, categoryResponse);
                            categoryResponse.setId(String.valueOf(category1.getId()));
                            categoryResponseList.add(categoryResponse);
                        }
                    });
                }
            }
            // 根据id去重
            List<CategoryResponse> categories = categoryResponseList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                                    () -> new TreeSet<>(Comparator.comparing(CategoryResponse::getId))),
                            ArrayList::new)
            );
            return RestResult.success(categories);
        } catch (Exception e) {
            log.error("9999", e);
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    //获取当前类目的二级类目
    public Category getParentCategoryObject(Category category, List<Category> categoryList) {
        if (category == null || category.getLevel() == null){
            return category;
        }
        if (category.getLevel() != null && category.getLevel() == 2) {
            return category;
        }
        Category category1 = new Category();
        Optional<Category> optionalCategory = categoryList.stream().filter(
                x -> Objects.equals(x.getId(), category.getParentId())
        ).findFirst();
        if (optionalCategory != null && optionalCategory.isPresent()){
            category1 = optionalCategory.get();
        }
        return getParentCategoryObject(category1, categoryList);
    }


    @Override
    public RestResult<List<CategoryResponse>> queryStoreSecondSonCategory(CategoryMerchantRelationRequest categoryMerchantRelationRequest) {
        try {
            log.info("jic-product===============》查询店铺二级下级分类,{}", categoryMerchantRelationRequest.toString());
            List<String> finalList = new ArrayList<>();
            List<Category> categoryList = new ArrayList<>();
            List<Category> categoryAllList = new ArrayList<>();
            Category category = categoryMapper.queryByPrimaryKey(categoryMerchantRelationRequest.getCategoryId());
            //获取当前类目的所有子级类目
            if (null != category) {
                categoryList.add(category);
                getSonCategory(finalList, categoryList);
            }
            //查询当前店铺的所有后台类目
            CategoryMerchantRelation categoryMerchantRelation = new CategoryMerchantRelation();
            categoryMerchantRelation.setDeptId(categoryMerchantRelationRequest.getDeptId());
            categoryMerchantRelation.setType(2);
            categoryMerchantRelation.setIsDisplay(1);
            List<CategoryMerchantRelation> list = categoryMerchantRelationMapper.query(categoryMerchantRelation);
            List<Long> categoryIds = new ArrayList<>();
            list.forEach(item -> {
                categoryIds.add(item.getCategoryId());
            });
            List<String> leftId = categoryTreeNodeRelationMapper.queryLeftIdByRightId(categoryIds);
            //获取交集
            finalList.retainAll(leftId);
            if (CollectionUtils.isNotEmpty(finalList)) {
                Category categoryRest = new Category();
                categoryRest.setType(2);
                categoryRest.setDeleteFlag(0);
                final List<Category> categoryAllRestList = categoryMapper.query(categoryRest);
                List<Category> categoryList1 = categoryMapper.queryByIds(finalList);
                categoryList1.forEach(item -> {
                    List<Category> allParentCategoryObject = getAllParentCategoryObject(item, categoryAllRestList, new ArrayList<Category>());
                    categoryAllList.addAll(allParentCategoryObject);
                });
            }
            // 根据id去重
            List<Category> categories = categoryAllList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                                    () -> new TreeSet<>(Comparator.comparing(Category::getId))),
                            ArrayList::new)
            );
            List<CategoryResponse> categoryResponseList=new ArrayList<>();
            categories.forEach(item->{
                CategoryResponse categoryResponse=new CategoryResponse();
                BeanUtils.copyProperties(item,categoryResponse);
                categoryResponse.setId(String.valueOf(item.getId()));
                categoryResponse.setParentId(String.valueOf(item.getParentId()));
                categoryResponseList.add(categoryResponse);
            });
            //数据组装
            List<CategoryResponse> treeMap = getTreeMap(categoryResponseList);
            return RestResult.success(treeMap);
        } catch (Exception e) {
            log.error("9999", e.getLocalizedMessage());
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    //获取当前二级类目的叶子节点
    public void getSonCategory(List<String> finalList, List<Category> categoryList) {
        for (Category category : categoryList) {
            List<String> children = new ArrayList<>();
            List<Category> categorySonList = new ArrayList<>();
            List<Category> categoryNoLeaves = new ArrayList<>();//非叶子子节点
            Category category1 = new Category();
            category1.setParentId(category.getId());
            category1.setDeleteFlag(0);
            categorySonList = categoryMapper.query(category1);

            for (Category category2 : categorySonList) {
                if (category2.getIsLeaves() == 1) {
                    children.add(String.valueOf(category2.getId()));
                } else {
                    categoryNoLeaves.add(category2);
                }
            }
            if (CollectionUtils.isEmpty(children)) {
                getSonCategory(finalList, categoryNoLeaves);
            } else {
                finalList.addAll(children);
            }
        }
    }

    //通过子节点获取所有父节点
    public List<Category> getAllParentCategoryObject(Category category, List<Category> categoryAllList, List<Category> categoryList) {
        if (category.getLevel() == 3) {
            categoryList.add(category);
            return categoryList;
        } else {
            categoryList.add(category);
        }
        Category category1 = categoryAllList.stream().filter(
                x -> Objects.equals(x.getId(), category.getParentId())
        ).findFirst().get();
        return getAllParentCategoryObject(category1, categoryAllList, categoryList);
    }

    public static List<CategoryResponse> getTreeMap(List<CategoryResponse> treeList) {
        List<CategoryResponse> parentTreeList = new ArrayList<CategoryResponse>();
        List<CategoryResponse> childrenTreeList = new ArrayList<CategoryResponse>();
        Map<String, String> allIdMap = new HashMap<String, String>();
        if (treeList == null || treeList.size() == 0) {
            return parentTreeList;
        }
        for (CategoryResponse tree : treeList){
            allIdMap.put(tree.getId(), tree.getId());
        }
        //遍历找出所有的根节点和非根节点
        for (CategoryResponse tree : treeList) {
            if (tree.getLevel()==3){
                parentTreeList.add(tree);
            }else{
                childrenTreeList.add(tree);
            }
        }
        //递归获取所有子节点
        if (parentTreeList != null && parentTreeList.size() > 0) {
            for (CategoryResponse tree : parentTreeList) {
                //添加所有子级
                List<CategoryResponse> children = getChildrenTreeList(childrenTreeList, tree.getId());
                tree.setCategoryList(children);
            }
        }
        return parentTreeList;
    }

    //递归查询子节点
    public static List<CategoryResponse> getChildrenTreeList(List<CategoryResponse> childrenList, String parentId) {
        List<CategoryResponse> parentTreeList = new ArrayList<CategoryResponse>();
        List<CategoryResponse> childrenTreeList = new ArrayList<CategoryResponse>();
        if (childrenList == null || childrenList.size() == 0) {
            return parentTreeList;
        }
        //找出所有的根节点和非根节点
        for (CategoryResponse tree : childrenList) {
            if (parentId.equals(tree.getParentId())) {
                parentTreeList.add(tree);
            } else {
                childrenTreeList.add(tree);
            }
        }
        //查询子节点
        if (parentTreeList != null && parentTreeList.size() > 0) {
            for (CategoryResponse tree : parentTreeList) {
                //递归查询子节点
                List<CategoryResponse> children = getChildrenTreeList(childrenTreeList, tree.getId());
                tree.setCategoryList(children);
            }
        }
        return parentTreeList;
    }




}